package com.example.provider01.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class Provide {

    @Autowired
    RedisTemplate redisTemplate;
    final String KEY01= "mylock01";
    final String KEY02= "mylock02";
    @GetMapping("/compete")
    public String compete(){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(KEY01, "value01");
        if (!flag){
            return "竞争失败，被B占用";
        }
        return "A竞争成功";
    }

    @GetMapping("/time")
    public String competeTimeOut(){
        boolean flag = redisTemplate.opsForValue().setIfAbsent(KEY02, "value02", 10, TimeUnit.SECONDS);
        if (redisTemplate.opsForValue().get(KEY02).equals("value02")){
            return "正在占用,"+KEY02+"将在"+  redisTemplate.getExpire(KEY02)   +"s后失效";
        }
        return "等待锁";
    }
}
